package com.iwop.moto.controller;

import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.util.StringUtil;
import com.iwop.moto.cache.RedisUtil;
import com.iwop.moto.cache.SerializeUtil;
import com.iwop.moto.comm.ConfLottery;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.model.*;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.LotteryUtils.CouponLotteryUtil;
import com.iwop.moto.utils.stringUtil.JsonUtils;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户付款抽奖接口
 * Created by chenzq on 2016/12/8.
 */
@Controller
public class FUserLotteryController extends BaseController {

    @Autowired
    private FUserLotteryService fUserLotteryService;

    @Autowired
    private FOrderServiceService fOrderServiceService;

    @Autowired
    private FCouponService fCouponService;

    @Autowired
    private MOrderPurchaseService mOrderPurchaseService;
    @Autowired
    private MPaymentService mPaymentService;

    @Autowired
    private MGPOrderService mgpOrderService;

    @Autowired
    private MCouponConfigService configService;

    Logger logger = Logger.getLogger(FUserLotteryController.class);


    /**
     * 功能描述 检查抽奖记录
     *
     * @param
     * @return
     */

    @RequestMapping(value = "/comsumer/lotter/index", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel index(@ApiParam(name = "order_id", value = "订单id")
                             @RequestParam(value = "order_id") String order_id,
                             @ApiParam(name = "user_id", value = "用户id")
                             @RequestParam(value = "user_id") String user_id) {
        Integer count = null;
        try {
            count = fUserLotteryService.findOneByUserIdAndOrderId(user_id, order_id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("抽奖记录查询错误: 【" + order_id + "】");
            return getErr(ErrCode.ERROR_SYSTEM);
        }
        if (count > 0) {
            return getErr(ErrCode.ERROR_USER_LOTTERY_HAVA_INFO);
        }
        return getSucceed(ErrCode.SUCCEED);
    }

    /**
     * 用户端抽奖接口
     *
     * @param order_id
     * @param user_id
     * @return
     */
    @RequestMapping(value = "/comsumer/lotter/action", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel comsumerIndex(@ApiParam(name = "order_id", value = "订单id")
                                     @RequestParam(value = "order_id") String order_id,
                                     @ApiParam(name = "user_id", value = "用户id")
                                     @RequestParam(value = "user_id") String user_id,
                                     @ApiParam(name = "c_type", value = "客户端类型")
                                     @RequestParam(value = "c_type") String c_type
    ) {
        /**
         * 订单验证
         */
        try {
            Double payMoney;
            try {
                if (switchClientTypeByOrderId(order_id).equals("user")) {
                    SuperRecordModel storeOrderByOrderNo = fOrderServiceService.getStoreOrderByOrderNo(order_id);
                    payMoney = ((BigDecimal) storeOrderByOrderNo.get("money")).doubleValue();
                } else if (switchClientTypeByOrderId(order_id).equals("business")) {
                    MOrderPurchase oneByPayOrderNo = mOrderPurchaseService.findOneByoutTradeNo(order_id);
                    payMoney = oneByPayOrderNo.getMoney();
                } else if (switchClientTypeByOrderId(order_id).equals("Ho")) {
                    MGPOrder mgpOrder = mgpOrderService.findOneBySid(order_id);
                    payMoney = mgpOrder.getMoney();
                } else {
                    return getErr("订单未找到");
                }
            } catch (Exception e) {
                logger.error("订单ID：" + order_id, e);
                return getErr("订单有问题");
            }
            if (payMoney == null) {
                return getErr(ErrCode.BANK_ERROR_MONEY_SUFF);
            }
            Integer count = fUserLotteryService.findOneByUserIdAndOrderId(user_id, order_id);
            if (count > 0) {
                return getErr(ErrCode.ERROR_USER_LOTTERY_HAVA_INFO);
            }


//            Map<Double[], Map<Integer[], String[]>> mapMap;
//            if (c_type.equals("user")) {
//                mapMap = CouponLotteryUtil.getInstance().initUserMap();
//            } else {
//                mapMap = CouponLotteryUtil.getInstance().initBusinessMap();
//            }
//
//            List<String> couponList = CouponLotteryUtil.getInstance().fuckYouCoupon(payMoney, mapMap);
            String clientType = "USER";
            if (c_type.equals("user")) {
                clientType = "USER";
            } else {
                clientType = "SELLER";
            }
            List<String> couponList = fUserLotteryService.getCouponListByClientTypeAndMoney(clientType, payMoney);
            Double money = null;
            SuperRecordModel data = null;
            if (couponList.size() == 1) {
                MCoupon mCoupon = fCouponService.getCouponById(couponList.get(0));
                money = mCoupon.getMoney();
                if (money == 0.0) {
                    fUserLotteryService.noLettery(order_id, user_id);
                    data = new SuperRecordModel();
                    data.put("couponType", "vouchers");
                    data.put("val", 0);
                    return getSucceed(data, ErrCode.SUCCEED);
                }
                fUserLotteryService.addUserCouponPackage(order_id, couponList, user_id);
                data = new SuperRecordModel();
                data.put("couponType", "vouchers");
                data.put("val", money);
                logger.info("维修店用户ID:【" + user_id + "】优惠券" + money);
            } else if (couponList.size() > 1) {
                fUserLotteryService.addUserCouponPackage(order_id, couponList, user_id);
                data = new SuperRecordModel();
                data.put("couponType", "package");
                data.put("val", "package");
                logger.info("维修店用户ID:【" + user_id + "】优惠券" + couponList.toString());
            } else {
                fUserLotteryService.noLettery(order_id, user_id);
                data = new SuperRecordModel();
                data.put("couponType", "vouchers");
                data.put("val", 0);
                return getSucceed(data, ErrCode.SUCCEED);
            }
            return getSucceed(data, ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户:" + user_id + "|| 订单ID:" + order_id + "抽奖出错");
            logger.error("FIND_BUG 【" + e + "】");
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 判断订单类型
     *
     * @param OrderId
     * @return
     */
    public String switchClientTypeByOrderId(String OrderId) {
        String str = OrderId.substring(0, 2);
        String clientType;
        switch (str) {
            case "SO":
                clientType = "user";
                break;
            case "Co":
                clientType = "business";
                break;
            case "Ho":
                clientType = "Ho";
                break;
            default:
                clientType = "other";
        }
        return clientType;

    }


    /**
     * 维修端抽奖接口
     *
     * @param order_id
     * @param user_id
     * @return
     */
    @RequestMapping(value = "/client/lotter/action", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel clientLottery(@ApiParam(name = "order_id", value = "订单id")
                                     @RequestParam(value = "order_id") String order_id,
                                     @ApiParam(name = "buyer_user_id", value = "维修店用户id")
                                     @RequestParam(value = "buyer_user_id") String buyer_user_id
    ) {
        /**
         * 订单验证
         */
        try {
            Double payMoney;
            try {
                if (switchClientTypeByOrderId(order_id).equals("user")) {
                    SuperRecordModel storeOrderByOrderNo = fOrderServiceService.getStoreOrderByOrderNo(order_id);
                    payMoney = ((BigDecimal) storeOrderByOrderNo.get("money")).doubleValue();
                } else if (switchClientTypeByOrderId(order_id).equals("business")) {
                    MOrderPurchase oneByPayOrderNo = mOrderPurchaseService.findOneByoutTradeNo(order_id);
                    payMoney = oneByPayOrderNo.getMoney();
                } else if (switchClientTypeByOrderId(order_id).equals("Ho")) {
                    MGPOrder mgpOrder = mgpOrderService.findOneBySid(order_id);
                    payMoney = mgpOrder.getMoney();
                } else {
                    logger.error("订单类型----->" + switchClientTypeByOrderId(order_id));
                    return getErr("订单未找到");
                }
            } catch (Exception e) {
                logger.error("订单ID:" + order_id, e);
                return getErr("订单有问题");
            }

            Integer count = fUserLotteryService.findOneByUserIdAndOrderId(buyer_user_id, order_id);
            if (count > 0) {
                logger.info("订单号【" + order_id + "】重复抽奖");
                return getErr(ErrCode.ERROR_USER_LOTTERY_HAVA_INFO);
            }
            SuperRecordModel data;
            if (payMoney < 10) {
                data = new SuperRecordModel();
                data.put("couponType", "vouchers");
                data.put("val", 0);
                logger.info("维修店用户ID:【" + buyer_user_id + "】优惠券" + 0);
                fUserLotteryService.noLettery(order_id, buyer_user_id);
                return getSucceed(data, ErrCode.SUCCEED);
            }
            if (payMoney < 15) {
                MCoupon mcoupon = cgetCouponByMoney(payMoney);
                if (mcoupon == null) {
                    logger.info("优惠券实体找不到");
                    return getErr(ErrCode.ERROR_SYSTEM);
                }
                if (mcoupon.getMoney() == 0) {
                    data = new SuperRecordModel();
                    data.put("couponType", "vouchers");
                    data.put("val", 0);
                    logger.info("维修店用户ID:【" + buyer_user_id + "】优惠券" + 0);
                    fUserLotteryService.noLettery(order_id, buyer_user_id);
                    return getSucceed(data, ErrCode.SUCCEED);
                }
                if (mcoupon != null) {
                    Double money = mcoupon.getMoney();
                    String coupon_id = mcoupon.getSid();
                    List<String> list = new ArrayList<>();
                    list.add(coupon_id);
                    fUserLotteryService.addClientCouponPackage(order_id, list, buyer_user_id);
                    data = new SuperRecordModel();
                    data.put("couponType", "vouchers");
                    data.put("val", money);
                    logger.info("维修店用户ID:【" + buyer_user_id + "】优惠券" + money);
                    return getSucceed(data, ErrCode.SUCCEED);
                }
            } else if (400 <= payMoney && payMoney < 1000) {
                List<String> list = new ArrayList<>();
                list.add(ConfLottery.十五抵用券); //15元
                fUserLotteryService.addClientCouponPackage(order_id, list, buyer_user_id);
                data = new SuperRecordModel();
                data.put("couponType", "package");
                data.put("val", "package");
                logger.info(buyer_user_id + "------------------命中15元");
                return getSucceed(data, ErrCode.SUCCEED);
            } else if (1000 <= payMoney && payMoney < 3000) {
                List<String> list = new ArrayList<>();
                list.add(ConfLottery.二十抵用券);//20元
                list.add(ConfLottery.十元抵用券);//10元
                fUserLotteryService.addClientCouponPackage(order_id, list, buyer_user_id);
                data = new SuperRecordModel();
                data.put("couponType", "package");
                data.put("val", "package");
                logger.info(buyer_user_id + "------------------命中20元和10元大礼包");
                return getSucceed(data, ErrCode.SUCCEED);
            } else if (3000 <= payMoney && payMoney < 6000) {
                List<String> list = new ArrayList<>();
                list.add(ConfLottery.二十抵用券);//20元
                list.add(ConfLottery.五十抵用券);//50元
                fUserLotteryService.addClientCouponPackage(order_id, list, buyer_user_id);
                data = new SuperRecordModel();
                data.put("couponType", "package");
                data.put("val", "package");
                logger.info(buyer_user_id + "------------------命中50元和20元大礼包");
                return getSucceed(data, ErrCode.SUCCEED);
            } else if (6000 <= payMoney && payMoney < 9000) {
                List<String> list = new ArrayList<>();
                list.add(ConfLottery.一百抵用券);//100元
                fUserLotteryService.addClientCouponPackage(order_id, list, buyer_user_id);
                data = new SuperRecordModel();
                data.put("couponType", "package");
                data.put("val", "package");
                logger.info(buyer_user_id + "------------------命中100元大礼包");
                return getSucceed(data, ErrCode.SUCCEED);
            } else if (9000 <= payMoney && payMoney < 13000) {
                List<String> list = new ArrayList<>();
                list.add(ConfLottery.二百抵用券);//100元
                fUserLotteryService.addClientCouponPackage(order_id, list, buyer_user_id);
                data = new SuperRecordModel();
                data.put("couponType", "package");
                data.put("val", "package");
                logger.info(buyer_user_id + "------------------命中200元");
                return getSucceed(data, ErrCode.SUCCEED);
            } else if (13000 <= payMoney) {
                List<String> list = new ArrayList<>();
                list.add(ConfLottery.一百抵用券);//100元
                list.add(ConfLottery.二百抵用券);//200元
                fUserLotteryService.addClientCouponPackage(order_id, list, buyer_user_id);
                data = new SuperRecordModel();
                data.put("couponType", "package");
                data.put("val", "package");
                logger.info(buyer_user_id + "------------------命中100元和200元大礼包");
                return getSucceed(data, ErrCode.SUCCEED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
        return getErr(ErrCode.ERROR_SYSTEM);
    }


    /**
     * 根据订单付款金额随机生成金额 查出抵用券
     *
     * @param money
     * @return
     */
    private MCoupon getCouponByMoney(double money) {

        BigDecimal userBouns = doDraw(money);
        if (userBouns == null) {
            userBouns = BigDecimal.ZERO;
        }
        SuperRecordModel srms = new SuperRecordModel();
        srms.put("money", userBouns.doubleValue() + "");
        srms.put("coupon_type", "gifts");
        MCoupon mCoupon = new MCoupon();
        mCoupon.setMoney(userBouns.doubleValue());
        mCoupon.setCouponType("gifts");
        return fCouponService.getCouponByMoney(mCoupon);
    }


    /**
     * 核心抽奖方法
     *
     * @return
     */
    private BigDecimal doDraw(double money) {
        try {
            BigDecimal userBouns = fUserLotteryService.doDraw(money);
            return userBouns;
        } catch (Exception e) {
            e.printStackTrace();
            return BigDecimal.ZERO;
        }
    }


    /**
     * 根据订单付款金额随机生成金额 查出抵用券
     *
     * @param money
     * @return
     */
    private MCoupon cgetCouponByMoney(double money) {

        BigDecimal userBouns = cdoDraw(money);
        SuperRecordModel srms = new SuperRecordModel();
        srms.put("money", userBouns.doubleValue() + "");
        srms.put("coupon_type", "gifts");
        MCoupon mCoupon = new MCoupon();
        mCoupon.setMoney(userBouns.doubleValue());
        mCoupon.setCouponType("gifts");
        return fCouponService.getCouponByMoney(mCoupon);
    }

    /**
     * 维修端核心抽奖方法
     *
     * @return
     */
    private BigDecimal cdoDraw(double money) {
        try {
            BigDecimal userBouns = fUserLotteryService.cdoDraw(money);
            return userBouns;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BigDecimal.ZERO;
    }
}
